package org.xtext.runtime.plan;

import is.lill.acre.conversation.Conversation;
import is.lill.acre.conversation.ConversationStatus;
import is.lill.acre.message.ACREMessage;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.xtext.runtime.acre.ACREService;
import org.xtext.runtime.formula.Predicate;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.messaging.AstraMessage;
import org.xtext.runtime.term.ITerm;
import org.xtext.runtime.term.Term;
import org.xtext.runtime.term.Variable;
import org.xtext.runtime.util.Bindings;
import org.xtext.runtime.util.EvaluateTermsVisitor;

/**
 * Implements the plan step for invoking an EIS action. 
 * @author rem
 *
 */
public class AcreForgetStep implements IPlanStep {
	private ITerm cid;
	
	public AcreForgetStep(ITerm cid) {
		this.cid = cid;
	}
	
	@Override
	public AcreForgetStep apply(Bindings set) {
		cid = cid.apply(set);
		return this;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handle(Agent agent, PlanStack planStack) {
		EvaluateTermsVisitor visitor = new EvaluateTermsVisitor(agent);
		Term<String> c_id = (Term<String>) cid.accept(visitor);
		
		Conversation con = agent.getConversationManager().getConversationByID(c_id.value());
		if (con == null) {
			agent.addBelief(new Predicate("unknownConversation", new ITerm[] {Term.newInstance(c_id.value())}));
		} else {
			agent.getConversationManager().forget( c_id.value() );
		}
	}

	@Override
	public String toString(String tabs) {
		return tabs + "acre_cancel(" + cid + ")";
	}
	
	public String toFullString(String tabs) {
		return toString(tabs);
	}
	
	@Override
	public Set<Variable> variables() {
		Set<Variable> vars = new HashSet<Variable>();
		if (cid instanceof Variable) vars.add((Variable) cid);
		return vars;
	}

	@Override
	public AcreForgetStep copy(Map<String, Variable> vars) {
		return new AcreForgetStep(cid.copy(vars));
	}

	public String toString() {
		return toString("");
	}

	@Override
	public void reset() {
	}
}